import "../sass/repassword.scss"


// 判断是否登陆过
const id = window.localStorage.getItem('id')
const token = window.localStorage.getItem('token')
if (!id) window.location.href = './login.html'

// 表单提交事件
const form = document.querySelector('.registerMain')
const oldPwdInp = document.querySelector('.reg_pwd')
const newPwdInp = document.querySelector('.reg_rpwd')
const rpwdInp = document.querySelector('.reg_nick')
const errBox = document.querySelector('.accountError1')

form.addEventListener('submit', async e => {
    e.preventDefault()
  
    //采集信息
    const info = {
      id,
      oldPassword: oldPwdInp.value,
      newPassword: newPwdInp.value,
      rNewPassword: rpwdInp.value
    }
  
    // 2-2. 各种验证
    if (!info.oldPassword || !info.newPassword || !info.rNewPassword) return alert('请完整填写表单')
    if (info.newPassword !== info.rNewPassword) return alert('两次密码不一致')
  
    const res = await $.ajax({
      url: 'http://localhost:8888/users/rpwd',
      method: 'POST',
      data: info,
      headers: { authorization: token }
    })

    if (res.code === 0) {
      // 修改失败
      errBox.style.display = 'block'
      return
    }
  
    if (res.code === 401) {
      // 登录状态过期
      window.location.href = './login.html'
      return
    }
  
    if (res.code === 1) {
      // 修改成功
      alert('修改密码成功, 点击确定重新登录')
      window.location.href = './login.html'
    }
})
  